#!/bin/sh

PREREQ=""
prereqs()
{
	echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
	prereqs
	exit 0
	;;
esac

# print production information
PROD_DATE="2025/08/01"
PROD_VERSION="v1.0.0"
printf "\nStart Automated Production...\n"
echo "###################################"
echo "#   Automated Production System    "
echo "#   Version: ${PROD_VERSION}       "
echo "#   Date:${PROD_DATE}              "
echo "###################################"

# download and extract rootfs
TMP_DIR="/tmp/product"
PRODUCT_SOURCE="${TMP_DIR}/source.xml"
PRODUCT_FILE="${TMP_DIR}/edisk.tar.gz"
PRODUCT_SHA1="${TMP_DIR}/edisk.sha1"

# Load and configure network interfaces 
configure_network()
{
	echo "Configuring network interfaces..."
	# Load network script
	. /scripts/network
}

# Download system edisk
download_sys_edisk()
{
	# Prompt for file server IP address
	read -p "Enter file server ip address: " file_server
    while true; do
        if validate_ipv4 "$file_server"; then
			break
        else
			read -p "Invalid input, Re-Input file server ip address: " file_server
        fi
    done
	# ping test file server
	ping -c 3 "$file_server" || {
		echo "Please check your network connection and try again."
		prepare_install
	}
	# tmp directory
	if [ -d ${TMP_DIR} ]; then
		rm -fr ${TMP_DIR} 
	fi
	mkdir -p ${TMP_DIR} 

	source_url="http://$file_server/product/source.xml"
	# Download with 3 retries
	wget -O "$PRODUCT_SOURCE" "$source_url" || {
		echo "Download source.xml file is failed!"
		download_sys_edisk
	}
	# Display numbered list of available images
	echo "Produce Available Image List:"
    grep -o 'name="[^"]*"' "$PRODUCT_SOURCE" | awk -F '"' '{print NR ") " $2}'
	# Get total number of entries
	total=$(grep -c 'name=' "$PRODUCT_SOURCE")

	# Get user selection
	read -p "Select Produce Image File (1-$total): " choice
    while true; do
		# Validate input is numeric
		if ! validate_integer "$choice"; then
			echo "Error: Invalid input. Please enter a number."
			read -p "Invalid Select,Re-Select (1-$total): " choice
		# Validate selection range
		elif [ "$choice" -lt 1 ] || [ "$choice" -gt "$total" ]; then
			echo "Error: Selection out of range. Please choose between 1 and $total."
			read -p "Invalid Select,Re-Select (1-$total): " choice
		else
            break
        fi
    done

	# Extract complete information for selected node
	selected_node=$(awk '/<img / {c++} c=='"$choice"'{print; exit}' "$PRODUCT_SOURCE")

	# Alternative formatting
	img_name=$(echo "$selected_node" | grep -o 'name="[^"]*"' | cut -d'"' -f2)
	img_file=$(echo "$selected_node" | grep -o 'file="[^"]*"' | cut -d'"' -f2)
	img_sha1sum=$(echo "$selected_node" | grep -o 'sha1sum="[^"]*"' | cut -d'"' -f2)

	# Print formatted output
	printf "\033[1;32m%-8s\033[0m: %s\n" "ImgName" "$img_name"
	printf "\033[1;32m%-8s\033[0m: %s\n" "ImgFile" "$img_file"
	printf "\033[1;32m%-8s\033[0m: %s\n" "ImgChecksum" "$img_sha1sum"
	
	# product img sha1sum
	echo "${img_sha1sum}  ${PRODUCT_FILE}" > "${PRODUCT_SHA1}"

	img_url="http://$file_server/product/$img_file"
	# Download with 3 retries
	wget -O "$PRODUCT_FILE" "$img_url" || {
		echo "System edisk download failed!"
		download_sys_edisk
	}
}

prepare_install()
{
	# Load and configure network interfaces
	configure_network
	# configure network interfaces sleep 2 seconds
	sleep 2
	# Download system edisk
	download_sys_edisk
}

# Prepare installation environment
prepare_install

# Verify downloaded file
if [ ! -f "$PRODUCT_FILE" ]; then
	echo "Downloaded file not found!"
	download_sys_edisk
fi

# Verify checksum file exists
if [ ! -f "$PRODUCT_SHA1" ]; then
    echo "Error: Checksum file $PRODUCT_SHA1 does not exist"
    download_sys_edisk
fi

# Perform SHA1 verification
echo "Verifying product img file..."
# Check verification result
if sha1sum -c "${PRODUCT_SHA1}"; then
    echo "product img file sha1sum verified successfully"
else
    echo "Error: product img file sha1sum failed verification"
    download_sys_edisk
fi

echo "Extracting product img file..."
tar -xzf "$PRODUCT_FILE" -C "$TMP_DIR"

INSTALL_SH="/tmp/product/install.sh"
# check install script
if [ ! -f "$INSTALL_SH" ]; then
	echo "product install script not found!"
	download_sys_edisk
fi

# call product install
. "$INSTALL_SH"
ret=$?
if [ "$ret" -eq 0 ]; then
	printf "\nProduct Install Complete...\n"
else
	printf "\nProduct Install Failed!\n"
	read -p "Press Enter to reboot! " REPLY
	if [ "$REPLY" -eq 5 ]; then
		exit 1
	fi
fi

# sync data write to disk
sync
